import { getAddressList, getSuggest } from '@mall/api/address'
import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import mall from "@src/store/mall";
import router from "@src/router";
import { getDistance } from "@src/common/utils";

Component({
  behaviors: [storeBindingsBehavior],
  storeBindings: [{
    store: mall,
    fields: ['userLocation'],
    actions: ['initLocation', 'setAddress']
  }],
  data: {
    isGetFocus: false,
    operateText: { first: '先逛逛', second: '添加为收货地址', thirdly: '取消' },
    hiddenOperate: true,
    //是否在定位中
    isLocation: false,
    region: ['广东省', '广州市', '海珠区'],
    searchAddressList: [],
    //地址列表
    locationList: [],
    //传给子组件的地址对象
    tempAddress: null
  },

  methods: {
    onLoad: function (options) {
    },
    relocationFunc() {
      const that = this;

      this.setData({ isLocation: true })
      this.initLocation(true).then((res) => {
        setTimeout(() => {
          that.setData({ isLocation: false })
        }, 1000)

      })

    },
    onLogin() {
      console.log('this.data.userAddress', this.data.userAddress)
      if (!this.data.userAddress) {
        this.setData({ isLocation: true })
        this.initLocation().then(() => {
          this.setData({ isLocation: false })
          console.log("userLocation", this.data.userLocation)
        }).catch(() => {
          this.setData({ isLocation: false })
        });
      }
      this.fetchData();
    },
    onShow() {
      this.fetchData();
    },
    showAddressList() {
      console.info("showAddressList")
      router.push({ name: "mall/address-list" })
    },
    //监听input是否获得焦点
    inputFocus(detail) {
      console.log('detail', detail.detail);
      this.setData({
        isGetFocus: detail.detail
      })
    },
    //监听input框的value值
    inputValueFunc(e) {
      const that = this;
      const region = that.data.region[1];
      if (e.detail && e.detail.length > 0) {
        // 调用api搜索方法
        that.setData({
          isGetFocus: true
        })
        getSuggest(e.detail, region).then(res => {
          console.log('获取搜索地址', res);
          let addList = res
          // getDistance(this.data.curLocation.latitude, this.data.curLocation.longitude, )
          console.info(res);
          if (this.data.userLocation) {
            addList.forEach(item => {
              let distance = getDistance(this.data.userLocation.latitude, this.data.userLocation.longitude, item.latitude, item.longitude)
              if (distance < 1000) {
                distance = distance + "米"
              } else {
                distance = (Math.round(distance / 100) / 10).toFixed(1) + "km"
              }
              item.distance = distance;
            })
          }
          that.setData({
            searchAddressList: addList
          })
        })
      } else {
        that.setData({
          searchAddressList: [],
          isGetFocus: false
        })
      }
    },
    //显示operate组件,并向该组件传值
    showAddressOperate(e) {
      console.log('e', e);
      let temp = e.currentTarget.dataset.locationobj;
      temp.addr = temp.title;
      this.setData({
        hiddenOperate: false,
        tempAddress: temp
      })
    },

    //监听选择城市
    bindRegionChange: function (e) {
      console.log('picker发送选择改变，携带值为', e.detail.value)
      this.setData({
        region: e.detail.value
      })
    },
    //进入新增收货地址页面
    goAddAddressPage() {
      router.push({
        name: 'mall/address-form',
        events: {
          'update': () => {
            this.fetchData();
          }
        }
      })
    },
    //拉取地址列表
    fetchData() {
      getAddressList().then(res => {
        if (res.code === 0) {
          this.setData({
            locationList: res.data
          })
        }
      })
    },
    //设置为收货地址
    selectAddress(e) {
      this.setAddress(e.currentTarget.dataset.obj);
      const eventChannel = this.getOpenerEventChannel()
      if (eventChannel && eventChannel.emit) {
        //向监听的上个页面传送数据
        eventChannel.emit('acceptDataFromOpenedPage', { address: e.currentTarget.dataset.obj });
      }
      wx.navigateBack()
    },
    //监听opera是否有添加收货地址隐藏事件发出
    hiddenOperateFunc() {
      //影藏搜索列表
      this.setData({
        isGetFocus: false
      })
    },
  }
})
